<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElCard, ElForm, ElFormItem, ElInput, ElButton, ElDialog, ElMessageBox, ElMessage } from "element-plus";
import { useTokenStore } from "@/stores/token"; // 导入 Pinia store
import router from "@/router";

const userInfo = ref({
    id: null,
    username: "",
    password: ""
});

const tokenStore = useTokenStore();

const logout = () => {
    tokenStore.removeToken();
    router.push('/login');
};

const showPasswordDialog = ref(false);
const newPassword = ref("");

const updatePassword = () => {
    if (newPassword.value === userInfo.value.password) {
        ElMessageBox.alert('新密码不能与旧密码相同', '错误', {
            confirmButtonText: '确定',
            type: 'error',
        });
        return;
    }
    ElMessageBox.confirm('你确定要修改密码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            const token = tokenStore.getToken();
            const response = await axios.patch('/api/user/updatePwd', null, {
                params: {
                    id: userInfo.value.id,
                    newPassword: newPassword.value
                },
                headers: {
                    Authorization: token
                }
            });
            if (response.data.code === 0) {
                ElMessageBox.alert('密码修改成功', '成功', {
                    confirmButtonText: '确定',
                    type: 'success',
                });
                showPasswordDialog.value = false;
                logout();
            } else {
                ElMessageBox.alert(response.data.message, '错误', {
                    confirmButtonText: '确定',
                    type: 'error',
                });
            }
        } catch (error) {
            ElMessageBox.alert('密码修改失败', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
        }
    }).catch(() => {
        ElMessageBox.alert('操作取消', '提示', {
            confirmButtonText: '确定',
            type: 'info',
        });
    });
};

const showUsernameDialog = ref(false);
const newUsername = ref("");

const updateUsername = async () => {
    try {
        const token = tokenStore.getToken();
        const response = await axios.put('/api/user/update', null, {
            params: {
                usernameBefore: userInfo.value.username,
                usernameAfter: newUsername.value
            },
            headers: {
                Authorization: token
            }
        });
        if (response.data.code === 0) {
            ElMessageBox.alert('用户名修改成功', '成功', {
                confirmButtonText: '确定',
                type: 'success',
            });
            showUsernameDialog.value = false;
            fetchUserInfo(); // 更新用户信息
        } else {
            ElMessageBox.alert(response.data.message, '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
        }
    } catch (error) {
        ElMessageBox.alert('用户名修改失败', '错误', {
            confirmButtonText: '确定',
            type: 'error',
        });
    }
};

const fetchUserInfo = async () => {
    try {
        const token = tokenStore.getToken();
        if (!token) {
            throw new Error('Token not found');
        }
        const response = await axios.get('/api/user/userdetail', {
            headers: {
                Authorization: token
            }
        });
        if (response.data.code === 0 && response.data.data) {
            userInfo.value = response.data.data;
        } else {
            throw new Error('Invalid response structure or error');
        }
    } catch (error) {
        console.error("获取用户信息失败", error);
        if (error.response && error.response.status === 401) {
            ElMessageBox.alert('请重新登录', '未授权', {
                confirmButtonText: '确定',
                type: 'error',
            }).then(() => {
                logout();
            });
        }
    }
};

onMounted(() => {
    fetchUserInfo();
});
</script>

<template>
    <el-card class="user-info-card" shadow="hover">
        <div class="card-header">
            <span>基本资料</span>
        </div>
        <el-form label-position="right" label-width="100px" class="user-info-form">
            <el-form-item label="账户">
                <el-input v-model="userInfo.username" autocomplete="username" class="fixed-width-input" disabled></el-input>
                <el-button type="primary" class="fixed-width-button" @click="showUsernameDialog = true">修改用户名</el-button>
            </el-form-item>
            <el-form-item label="密码">
                <el-input
                        v-model="userInfo.password"
                        :type="showPassword ? 'text' : 'password'"
                        autocomplete="current-password"
                        class="fixed-width-input"
                        disabled
                        show-password>
                </el-input>
                <el-button type="primary" class="fixed-width-button" @click="showPasswordDialog = true">修改密码</el-button>
            </el-form-item>
            <el-form-item class="centered-form-item">
                <el-button type="primary" class="fixed-width-button-logout" @click="logout">退出登录</el-button>
            </el-form-item>
        </el-form>

        <!-- 修改密码对话框 -->
        <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
            <el-form>
                <el-form-item label="新密码">
                    <el-input v-model="newPassword" type="password" show-password></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确定</el-button>
        </span>
            </template>
        </el-dialog>

        <!-- 修改用户名对话框 -->
        <el-dialog v-model="showUsernameDialog" title="修改用户名" width="400px">
            <el-form>
                <el-form-item label="新用户名">
                    <el-input v-model="newUsername"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUsernameDialog = false">取消</el-button>
          <el-button type="primary" @click="updateUsername">确定</el-button>
        </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style scoped>
.user-info-card {
    max-width: 650px; /* 调整为合适的宽度 */
    margin: 20px auto; /* 水平居中，垂直有间隔 */
    border: 1px solid #c2c2c2; /* 轻微的边框，与 Element UI 风格保持一致 */
}

.card-header {
    font-size: 20px;
    font-weight: bold;
    padding: 12px 20px; /* 增加内边距以创建更多空间 */
    border-bottom: 1px solid #ebeef5; /* 与卡片主体部分稍微区分 */
}

.user-info-form {
    padding: 20px;
}

.el-form-item {
    display: flex;
    align-items: center;
}

.el-input {
    flex: none;
    width: 300px; /* 固定宽度 */
}

.el-button {
    flex: none;
    margin-left: 10px;
    width: 120px; /* 固定宽度 */
}

.fixed-width-input {
    width: 300px;
}

.fixed-width-button {
    width: 120px;
}

.centered-form-item {
    display: flex;
    justify-content: center; /* 使其居中对齐 */
}

.fixed-width-button-logout {
    width: 340px; /* 设置合适的宽度 */
    text-align: center;
}

.dialog-footer {
    text-align: right;
}
</style>
